package jp.co.shinesoft.jpetstore.genericdao;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.util.ClassUtils;

import java.util.List;

@SuppressWarnings("unchecked")
public class GenericDaoImpl<T> extends SqlMapClientDaoSupport implements GenericDao<T> {

    private Class<T> persistentClass;

    public Long insert(T object) {
        return (Long) getSqlMapClientTemplate().insert(GenericDaoQueryNameUtil.getInsertQueryName(getClassName()), object);
    }

     public T findByKey(Long id) {
         return (T) getSqlMapClientTemplate().queryForObject(GenericDaoQueryNameUtil.getSelectByKeyQueryName(getClassName()), id);
     }

    public List<T> findByExample(T object) {
        return getSqlMapClientTemplate().queryForList(GenericDaoQueryNameUtil.getSelectByExampleQueryName(getClassName()), object);
    }

    public int updateByKey(T object) {
        return getSqlMapClientTemplate().update(GenericDaoQueryNameUtil.getUpdateByKeyQueryName(getClassName()), object);
    }

    public int updateByExample(T object) {
        return getSqlMapClientTemplate().update(GenericDaoQueryNameUtil.getUpdateByExampleQueryName(getClassName()), object);
    }

    public int removeByKey(Long id) {
        return getSqlMapClientTemplate().delete(GenericDaoQueryNameUtil.getDeleteByKeyQueryName(getClassName()), id);
    }

    public int removeByExample(T example) {
        return getSqlMapClientTemplate().delete(GenericDaoQueryNameUtil.getDeleteByExampleQueryName(getClassName()), example);
    }

    private String getClassName() {
        return ClassUtils.getShortName(this.persistentClass);
    }
}
